package us.quizgame.quiz;

//import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Random;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.Timer;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.UIManager;
import javax.swing.ImageIcon;

import us.quizgame.Menu;
import us.quizgame.database.Database;
import us.quizgame.database.Question;



import java.awt.Font;

public abstract class QuizGame extends JFrame
{
	protected final int LENGTH_OF_GAME = 5;
	protected final int NUM_OF_QUESTIONS = 10;

	protected JPanel contentPane;
	protected JButton button1;
	protected JButton button2;
	protected JLabel scoreLbl;
	protected JTextPane questionTxt;
	
	protected Question[] questions;
	protected Database db = new Database();
	protected int questionSub = 0;
	protected int elapsedQuestionTime = 0;
	
	public int score = 0;
	public int totalGameTime = 0;
	public String gameMode;
	public boolean[] userAnswers = new boolean[NUM_OF_QUESTIONS];
	public static final String[] gameModes = {"normal","survival"};
	
	//timers
	Timer mainTimer;
	Timer resetQuestionTimer;
	protected JLabel lblUpArrow;
	private JLabel mlabel;
	
	/**
	 * Create the frame.
	 */
	public QuizGame()
	{
		setResizable(false);
		setTitle("The XTR3M3 Quiz Game");
		setFocusable(true);
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_UP)
				{
					button1.doClick();
				}
				else if (e.getKeyCode() == KeyEvent.VK_DOWN)
				{
					button2.doClick();
				}
			}
		});
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 550, 450);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.setBackground(Color.black);
		
		JLabel lblDownArrow = new JLabel("Down Arrow");
		lblDownArrow.setForeground(Color.GRAY);
		lblDownArrow.setBackground(UIManager.getColor("Button.background"));
		lblDownArrow.setBounds(84, 268, 77, 23);
		contentPane.add(lblDownArrow);
		
		lblUpArrow = new JLabel("Up Arrow");
		lblUpArrow.setBackground(UIManager.getColor("Button.darkShadow"));
		lblUpArrow.setForeground(Color.GRAY);
		lblUpArrow.setBounds(84, 140, 61, 16);
		contentPane.add(lblUpArrow);
		lblUpArrow.setLabelFor(button1);
		
		
		button2 = new JButton("New button");
		button2.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkAnswer(button2);
			
			}
		});
		button2.setOpaque(true);
		button2.setBackground(UIManager.getColor("Button.foreground"));
		button2.setBounds(51, 258, 471, 121);
		contentPane.add(button2);
		
		button1 = new JButton("New button");
		button1.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkAnswer(button1);
			}
		});
		button1.setOpaque(true);
		button1.setBackground(UIManager.getColor("Button.foreground"));
		button1.setBounds(51, 125, 471, 121);
		contentPane.add(button1);

		
		questionTxt = new JTextPane();
		questionTxt.setFont(new Font("Lucida Grande", Font.BOLD, 16));
		questionTxt.setEditable(false);
		questionTxt.setBounds(113, 57, 302, 47);
		questionTxt.setBackground(null);
		questionTxt.setForeground(Color.white);
		contentPane.add(questionTxt);
		
		scoreLbl = new JLabel("Score: 0");
		scoreLbl.setBounds(461, 29, 83, 10);
		scoreLbl.setForeground(Color.white);
		contentPane.add(scoreLbl);
		
		mlabel = new JLabel("New label");
		mlabel.setIcon(new ImageIcon(QuizGame.class.getResource("/us/quizgame/images/blood-drip.gif")));
		mlabel.setBounds(38, 0, 434, 288);
		contentPane.add(mlabel);
			
		questions = db.fetchQuestions(10);
		
		mainTimer = createMainTimer();
		resetQuestionTimer = createResetQuestionTimer();
		initGame();	
	}
	
	/* 
	 * Methods that deal with setting up the game
	 */
	protected void initGame()
	{
		//start the main timer
		setEnabled();
		mainTimerStart();
		setFields();
	}
	
	//each class that inherits QuizGame should decide how the game ends
	protected abstract void endGame();

	protected void checkAnswer(JButton button)
	{
		setDisabled();
			
		if (button.getText().equals(questions[questionSub].getCorrectAnswer()))
		{
			userAnswers[questionSub] = true;
			correctAnswer(button);
		}
		else
		{
			userAnswers[questionSub] = false;
			wrongAnswer(button);
		}
	}

	/*
	 * initializers/setters for the GUI
	 */
	protected void setFields()
	{
		questionTxt.setText(questions[questionSub].getQuestion());
		
		//retrieve random number between 0 or 1 to randomize the buttons
		Random rand = new Random();		
		int  n = rand.nextInt(2);
		
		if (n == 0)
		{
			button1.setText(questions[questionSub].getCorrectAnswer());
			button2.setText(questions[questionSub].getWrongAnswer());
		}
		else
		{
			button1.setText(questions[questionSub].getWrongAnswer());
			button2.setText(questions[questionSub].getCorrectAnswer());
		}
		
	}
	
	protected void setDisabled()
	{
		button1.setEnabled(false);
		button2.setEnabled(false);
	}
	
	protected void setEnabled()
	{
		button1.setEnabled(true);
		button2.setEnabled(true);
	}
	
	 //Used to set all the gui back to the state it was at the start
	protected void resetGui()
	{
		Color defaultColor = new Color(240,240,240);
		
		button1.setBackground(UIManager.getColor("Button.foreground"));
		button2.setBackground(UIManager.getColor("Button.foreground"));
		contentPane.setBackground(Color.black);
	}
	

	/*
	 * Timers for GUI
	 */
	
	//if you override make sure to call resetQuestionTimerStart;
	public Timer createMainTimer()
	{		
		return new Timer(1000, new ActionListener() 
		{
			@Override
		    public void actionPerformed(ActionEvent ae) 
		    {
				totalGameTime++;
		    	elapsedQuestionTime++;
		    	System.out.println("MainTimer");
		    	switch (elapsedQuestionTime)
		    	{
			    	case LENGTH_OF_GAME / 2:
			    		Color darkOrange = new Color(217, 122, 28);
			    		contentPane.setBackground(darkOrange);
			    		break;
			    	case (LENGTH_OF_GAME - 1):
			    		Color darkRed = new Color(173, 0, 0);
			    		contentPane.setBackground(darkRed);
			    		break;
			    	case LENGTH_OF_GAME:
			    		//method for dealing with what happens when time runs out
						timeOut();						
			    		break;
		    	}
		    }
		});
	}
	
	protected Timer createResetQuestionTimer()
	{
		return new Timer(1000, new ActionListener() 
		{
		    @Override
		    public void actionPerformed(ActionEvent ae) 
		    {
		    	resetGui();
				//make sure we haven't reached the end of the game
				if (questionSub != 9)
				{
					questionSub++;
					//re-initialize the game
					initGame();
				}
				else
				{
					//reached the end of the game			
					endGame();
				}
		    }
		});
	}
	
	protected void mainTimerStart()
	{
		elapsedQuestionTime = 0;
		mainTimer.start();
	}

	protected void resetQuestionTimerStart()
	{
		mainTimer.stop();
		resetQuestionTimer.setRepeats(false); // Only execute once
		resetQuestionTimer.start(); 		
	}
	
	protected void timeOut()
	{
		setDisabled();
		button1.setText("Time out!");
		button2.setText("Time out!");
		button1.setBackground(Color.red);
		button2.setBackground(Color.red);
			//start the reset Question Timer since maintimer timed out
		resetQuestionTimerStart();	
	}
	
	protected void correctAnswer(JButton button)
	{
		button.setText("Correct!");
		button.setBackground(Color.green);
		scoreLbl.setText("Score: " + ++score);
		
		//Sounds played upon scores
		if (score == 1)
			playSound(Menu.class.getResource("/us/quizgame/media/firstblood.wav"));
		
		if (score == 3)
			playSound(Menu.class.getResource("/us/quizgame/media/triplekill.wav"));
		
		if (score == 5)
			playSound(Menu.class.getResource("/us/quizgame/media/headshot.wav"));
		
		if (score == 7)
			playSound(Menu.class.getResource("/us/quizgame/media/megakill.wav"));
		
		if (score == 9)
			playSound(Menu.class.getResource("/us/quizgame/media/monsterkill.wav"));
	}
	
	protected void wrongAnswer(JButton button)
	{
		button.setText("Wrong!");
		button.setBackground(Color.red);
	}
	
	public Question[] getQuestions() {
		return questions;
	}
	
	public void playSound(URL url)
	{
        try {
            AudioInputStream stream = AudioSystem.getAudioInputStream(url);
            AudioFormat format = stream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(stream);
            clip.start();
        }
        
        catch(Exception e)
        {
        }
	}
	
}
